package com.zn.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zn.config.NativeMemoryConfig;
import com.zn.entity.*;
import com.zn.mapper.OptionTradingContractMapper;
import com.zn.mapper.OptionTradingGoodsMapper;
import com.zn.service.MdInfoService;
import com.zn.util.*;
import com.zn.vo.*;
import com.zn.web.dto.KLineDto;
import com.zn.web.rpc.MdRemoteCall;
import com.zn.web.vo.*;
import com.zn.websocket.group.ChannelGroups;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DurationFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.ExecutionException;

/**
 * Created by yinjiawei on 2018/7/14.
 */
@Service
public class MdInfoServiceImpl implements MdInfoService {
    private static final Logger LOGGER = LoggerFactory.getLogger(MdInfoServiceImpl.class);
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private OptionTradingGoodsMapper optionTradingGoodsMapper;
    @Autowired
    private OptionTradingContractMapper optionTradingContractMapper;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private MdRemoteCall mdRemoteCall;
    @Override
    public OptionTradingGoods selectBytradingGoodsCode(String tradingGoodsCode){
        return optionTradingGoodsMapper.selectBytradingGoodsCode(tradingGoodsCode);
    }

    @Override
    public List<OptionTradingGoods> findtradingGoodsCodeAll(){
        return optionTradingGoodsMapper.findAll();
    }

    @Override
    public List<OptionTradingContract> selectIsTrading(){
        return optionTradingContractMapper.selectIsTrading();
    }


    @Override
    public void saveTgAndInstrumentMonth(String targetCode, Set<String> instrumentMonths) {
        OptionTradingGoods optionTradingGoods=optionTradingGoodsMapper.selectBytradingGoodsCode(targetCode);
        if (optionTradingGoods ==null){
            Object etfObj=redisTemplate.opsForHash().get(Constant.TARGET_CODE_LIST, targetCode);
            EtfMdInfo etfMdInfo=JSONObject.parseObject(etfObj.toString(),EtfMdInfo.class);
            optionTradingGoods=new OptionTradingGoods();
            optionTradingGoods.setTradingGoodsId(UUIDUtils.getUuid());
            optionTradingGoods.setTradingGoodsCode(targetCode);
            optionTradingGoods.setTradingGoodsName(etfMdInfo.getEtfName());
            optionTradingGoodsMapper.insertSelective(optionTradingGoods);
        }else{
            /**将所有的合约月份设置成 不可交易**/
            optionTradingContractMapper.setIsTradingDisabled();
            for(String instrumentMonth:instrumentMonths){
                OptionTradingContract optionTradingContract=optionTradingContractMapper.selectByGoodsIdAndMonth(optionTradingGoods.getTradingGoodsId(), instrumentMonth);
                if(optionTradingContract!=null){
                    //如果存在 则将合约月份设置成可交易
                    optionTradingContract.setIsTrading(0);
                    optionTradingContractMapper.updateByPrimaryKeySelective(optionTradingContract);
                }else{
                    //如果不存在则新增
                    optionTradingContract=new OptionTradingContract();
                    OptionTradingContract optionTradingContractLast=optionTradingContractMapper.selectLastByGoodsId(optionTradingGoods.getTradingGoodsId());
                    if(optionTradingContractLast!=null){
                        optionTradingContract.setOpenFee(optionTradingContractLast.getOpenFee() == null ? new BigDecimal(0): optionTradingContractLast.getOpenFee());
                        optionTradingContract.setCloseFee(optionTradingContractLast.getCloseFee()== null ? new BigDecimal(0):optionTradingContractLast.getCloseFee());
                        optionTradingContract.setCostOpenFee(optionTradingContractLast.getCostOpenFee()== null ? new BigDecimal(0):optionTradingContractLast.getCostOpenFee());
                        optionTradingContract.setCostCloseFee(optionTradingContractLast.getCostCloseFee()== null ? new BigDecimal(0):optionTradingContractLast.getCostCloseFee());
                    }else{
                        optionTradingContract.setOpenFee(new BigDecimal(0));
                        optionTradingContract.setCloseFee(new BigDecimal(0));
                        optionTradingContract.setCostOpenFee(new BigDecimal(0));
                        optionTradingContract.setCostCloseFee(new BigDecimal(0));
                    }
                    optionTradingContract.setContractGoodsId(UUIDUtils.getUuid());
                    optionTradingContract.setTradingGoodsId(optionTradingGoods.getTradingGoodsId());
                    optionTradingContract.setContractMonthName(instrumentMonth);
                    optionTradingContract.setIsTrading(0);
                    optionTradingContract.setCreateTime(new Date());
                    optionTradingContract.setUpdateTime(new Date());
                    optionTradingContractMapper.insertSelective(optionTradingContract);
                }
            }
        }

    }

    /**
     * 首页获取所有标的信息和日期
     *
     * @return
     *  targetList   所有标的信息
     *  targetDateList  当前标的交易日期
     *  execList   当前标的首个交易日期行权价格
     *  manyHyMdInfoList   认购合约
     *  emptyHyMdInfoList  认沽合约
     */
    @Override
    public Map<String, List<?>> getTargetList(){
        //初始化
        Map<String, List<?>> targetMap = new HashMap<String, List<?>>();
        //获取所有标的信息
        Map<Object, Object> mapTarget = redisTemplate.opsForHash().entries(Constant.TARGET_CODE_LIST);
        //判断是否存在标的信息
        if (mapTarget.size() > 0){
            List<EtfMdInfo> etfMdInfoList = new LinkedList<EtfMdInfo>();
            List<TradingGoodsVo> targetList = new LinkedList<TradingGoodsVo>();
            List<TradingDateVo> targetDateList = new LinkedList<TradingDateVo>();
            int i = 0;
            for (Object key : mapTarget.keySet()){
                EtfMdInfo etfMdInfo = JSONObject.parseObject(mapTarget.get(key).toString(), EtfMdInfo.class);
                TradingGoodsVo target = new TradingGoodsVo();
                target.setTradingGoodsName(etfMdInfo.getEtfName());
                target.setTradingGoodsCode(key.toString());
                targetList.add(target);
                if ( i == 0) {
                    //获取标的最新价
                    etfMdInfoList.add(etfMdInfo);
                    i++;
                }
            }
            //获取默认第一个标的最新交易日期
            String key = checkRedisKey(Constant.INSTRUMENT_MONTH_SET+targetList.get(0).getTradingGoodsCode());
            Set<String> targetDateSet = redisTemplate.opsForSet().members(key);
            for (String ym: targetDateSet){
                TradingDateVo hyDate = new TradingDateVo();
                hyDate.setContractMonth(ym);
                targetDateList.add(hyDate);
            }

            //按交易日期升序
            Collections.sort(targetDateList, new Comparator<TradingDateVo>() {
                @Override
                public int compare(TradingDateVo o1, TradingDateVo o2) {
                    return o1.getContractMonth().compareTo(o2.getContractMonth());
                }
            });
            targetMap.put("target", targetList);
            targetMap.put("hyDate", targetDateList);
            targetMap.put("etfMdInfo", etfMdInfoList);
        }
        return targetMap;
    }

    /**
     * 根据标的与交易日期获取最新价
     * @param record  标的序号
     * @param record  交易日期
     * @return
     */
    @Override
    public Map<String, List<?>> findTargetList (TradingVo record) throws ParseException {

        //初始化
        Map<String, List<?>> targetMap = new HashMap<String, List<?>>();
        List<TradingDateVo> targetDateList = new LinkedList<TradingDateVo>();
        List<OptionSymbol> statInfoList = new LinkedList<OptionSymbol>();
        List<EtfMdInfo> etfMdInfoList = new LinkedList<EtfMdInfo>();
        List<StrikePriceGoodsVo> execList = new LinkedList<StrikePriceGoodsVo>();

        //判断是否传递标的信息
        if (StringUtils.isBlank(record.getTradingGoodsCode())){
            return targetMap;
        }

        //判断是否传递标的交易日期
        if (StringUtils.isBlank(record.getInstrumentMonth())){
            //根据标的获取交易日期
            String key = checkRedisKey(Constant.INSTRUMENT_MONTH_SET+record.getTradingGoodsCode());
            Set<String> targetDateSet = redisTemplate.opsForSet().members(key);
            for (String ym : targetDateSet){
                TradingDateVo tradingDateVo = new TradingDateVo();
                tradingDateVo.setContractMonth(ym);
                targetDateList.add(tradingDateVo);
            }
            record.setInstrumentMonth(targetDateList.get(0).getContractMonth());

            //获取标的最新价
            String OEtfMdInfo = redisTemplate.opsForHash().get(Constant.TARGET_CODE_LIST, record.getTradingGoodsCode()).toString();
            EtfMdInfo etfMdInfo = JSONObject.parseObject(OEtfMdInfo, EtfMdInfo.class);
            etfMdInfoList.add(etfMdInfo);
        }

        //获取标的默认第一个日期最新行权价
        String key = checkRedisKey(Constant.EXECS_PRICE_SET + record.getTradingGoodsCode() + ":" + record.getInstrumentMonth());
        Set<String> targetExecSet = redisTemplate.opsForSet().members(key);
        for (String targetExec : targetExecSet){
            StrikePriceGoodsVo exec = new StrikePriceGoodsVo();
            exec.setStrikePrice(targetExec);
            execList.add(exec);
        }

        //获取标的默认第一个日期最新合约价
//        key = checkRedisKey(Constant.OPTION_SYMBOL_INFO);
//        List<Object> reslutMapList = redisTemplate.opsForHash().values(key);
//        for (Object obj : reslutMapList){
//            statInfoList.add(JSONObject.parseObject(obj.toString(), OptionSymbol.class));
//        }

        key = checkRedisKey(Constant.OPTION_TICKL_INFO+record.getTradingGoodsCode()+":"+record.getInstrumentMonth());
        Map<Object, Object> map = redisTemplate.opsForHash().entries(key);

        //排序获取最新行权价和对应认购认沽信息
        targetMap = this.mateNewTarget(record.getTradingGoodsCode(), execList, map);

        //请求新标的返回交易日期
        if (targetDateList.size() > 0){
            //按交易日期升序
            Collections.sort(targetDateList, new Comparator<TradingDateVo>() {
                @Override
                public int compare(TradingDateVo o1, TradingDateVo o2) {
                    return o1.getContractMonth().compareTo(o2.getContractMonth());
                }
            });
            targetMap.put("hyDate", targetDateList);
            targetMap.put("etfMdInfo", etfMdInfoList);
        }

        if (!"".equals(record.getType()) && record.getType() != null) {
            //其它获取所有
            switch (record.getType()) {
                case "1"://获取认购
                    targetMap.remove("sellHy");
                    break;
                case "2"://获取认沽
                    targetMap.remove("buyHy");
                    break;
            }
        }
        return targetMap;
    }

    /**
     * 通过排序行权价匹配最新认购、认沽信息
     *
     * @param execList      标的最新行权价
     * @param map          当天合约信息
     * @return
     *      execList    最新行权价
     *      manyHyMdInfoList    认购合约
     *      emptyHyMdInfoList    认沽合约
     */

    public Map<String, List<?>> mateNewTarget(String tradingGoodsCode, List<StrikePriceGoodsVo> execList, Map<Object, Object> map) throws ParseException{
        //初始化
        Map<String, List<?>> targetMap = new HashMap<String, List<?>>();
        List<OptionMarketDataField> buyOptionMarketDataList = new LinkedList<OptionMarketDataField>();
        List<OptionMarketDataField> sellOptionMarketDataList = new LinkedList<OptionMarketDataField>();
        List<OptionMarketDataField> OptionMarketDataList = new LinkedList<OptionMarketDataField>();
        List<String> optionMarketLey = new ArrayList<String>();
        String optionSymbolKey = "";
        //获取商品的交易开始时间，判断是否获取前一天数据
        Object obj = redisTemplate.opsForValue().get(Constant.TRADE_DATE_INFO + tradingGoodsCode);
        OptionTradingGoods optionTradingGoods = JSON.parseObject(obj.toString(), OptionTradingGoods.class);
        String[] tradingTime = optionTradingGoods.getTradingTime().split("\\|");
        String[] time = tradingTime[0].split("\\-");
        Date date = DateUtils.convertStringToDate("yyyy-MM-dd HH:mm", DateUtils.formatDate("yyyy-MM-dd HH:mm", new Date()));
        Date tradingdate = DateUtils.convertStringToDate("yyyy-MM-dd HH:mm", DateUtils.formatDate(date)+" "+time[0]);
        if (tradingdate.getTime() > date.getTime()){
            optionSymbolKey = checkRedisKey(Constant.OPTION_SYMBOL_INFO);
        }else {
            String today = getWorkDate(DateUtils.formatDate("yyyy-MM-dd", new Date()));
            optionSymbolKey = Constant.OPTION_SYMBOL_INFO + today;
        }
        //按行权价升序
        Collections.sort(execList, new Comparator<StrikePriceGoodsVo>() {
            @Override
            public int compare(StrikePriceGoodsVo o1, StrikePriceGoodsVo o2) {
                return o1.getStrikePrice().compareTo(o2.getStrikePrice());
            }
        });
        Map<Object, Object> optionSymbolMap = redisTemplate.opsForHash().entries(optionSymbolKey);
        for (Object key : map.keySet()){
            OptionMarketDataField record = JSONObject.parseObject(map.get(key).toString(), OptionMarketDataField.class);
            Object optionSymbolObj=optionSymbolMap.get(key);
            if(optionSymbolObj!=null){
                OptionSymbol optionSymbol=JSONObject.parseObject(optionSymbolObj.toString(),OptionSymbol.class);
                record.setExecsPrice(optionSymbol.getExecsPrice());
                record.setInstrumentType(optionSymbol.getInstrumentType());
                record.setDeliveryYear(optionSymbol.getDeliveryYear());
                record.setDeliveryMonth(optionSymbol.getDeliveryMonth());
                record.setInstrumentMonth(optionSymbol.getInstrumentMonth());
                record.setInstrumentType(optionSymbol.getInstrumentType());
                record.setTargetCode(optionSymbol.getTargetCode());
                record.setRemainderDays(optionSymbol.getRemainderDays());
                record.setExpireDay(optionSymbol.getExpireDay());
                record.setInstrumentName(optionSymbol.getInstrumentName());
                record.setPreClosePrice(optionSymbol.getPreClosePrice());
            }
            OptionMarketDataList.add(record);
            optionMarketLey.add(key.toString());
        }
        for (StrikePriceGoodsVo exec : execList){
            int a = 0;
            for (int i = 0; i < OptionMarketDataList.size(); i++){
                //对比行权价
                if (exec.getStrikePrice().equals(OptionMarketDataList.get(i).getExecsPrice())){
                    if (optionSymbolMap.containsKey(optionMarketLey.get(i))) {
                        a++;
                        //判断区分认购和认沽信息
                        switch (OptionMarketDataList.get(i).getInstrumentType()) {
                            case "1":
                                buyOptionMarketDataList.add(OptionMarketDataList.get(i));
                                OptionMarketDataList.remove(i);
                                i--;
                                break;
                            case "2":
                                sellOptionMarketDataList.add(OptionMarketDataList.get(i));
                                OptionMarketDataList.remove(i);
                                i--;
                                break;
                        }
                    }
                }
                //已获取到全部合约信息
                if (a == 2){
                    break;
                }
                //确实部分合约信息，传入空值
                if (i+1 == OptionMarketDataList.size()){
                    OptionMarketDataField optionMarketDataField = new OptionMarketDataField();
                    if (buyOptionMarketDataList.size() > sellOptionMarketDataList.size()){//少认沽传入空
                        sellOptionMarketDataList.add(optionMarketDataField);
                    }else if (sellOptionMarketDataList.size() > buyOptionMarketDataList.size()) {//少认购传入空
                        buyOptionMarketDataList.add(optionMarketDataField);
                    }else {//缺少对应两条合约数据
                        sellOptionMarketDataList.add(optionMarketDataField);
                        buyOptionMarketDataList.add(optionMarketDataField);
                    }
                }
            }
        }

        targetMap.put("exec", execList);
        targetMap.put("buyHy", buyOptionMarketDataList);
        targetMap.put("sellHy", sellOptionMarketDataList);

        return targetMap;
    }

    /**
     * 获取工作日日期
     * @param today
     * @return
     */
    private String getWorkDate(String today){
        try {
            Response response=mdRemoteCall.checkHoliday(today);
            if(response.getDayType()!=0){
                Date yesterday=DateUtils.minusDay(DateUtils.convertStringToDate(today),1);
                today=this.getWorkDate(DateUtils.formatDate("yyyy-MM-dd", yesterday));
            }
            return today;
        }catch (Exception e){
            LOGGER.error("getWeekDateError-------->",e);
            return null;
        }
    }

    /**
     * 获取合约最新详情价
     * @param record
     * @return
     */
    @Override
    public OptionMarketDataField getTargetContract(TradingVo record) throws ParseException{
        //获取合约最新信息
        String key = checkRedisKey(Constant.OPTION_TICKL_INFO+record.getTradingGoodsCode()+":"+record.getInstrumentMonth());
        Object reslut = redisTemplate.opsForHash().get(key, record.getInstrumentCode());
        OptionMarketDataField optionMarketDataField = JSONObject.parseObject(reslut.toString(), OptionMarketDataField.class);
        String nowDate=this.getWorkDate(DateUtils.convertDateToString(new Date()));
        String optionSymbolKey = "";
        //获取商品的交易开始时间，判断是否获取前一天数据
        Object obj = redisTemplate.opsForValue().get(Constant.TRADE_DATE_INFO + record.getTradingGoodsCode());
        OptionTradingGoods optionTradingGoods = JSON.parseObject(obj.toString(), OptionTradingGoods.class);
        String[] tradingTime = optionTradingGoods.getTradingTime().split("\\|");
        String[] time = tradingTime[0].split("\\-");
        Date date = DateUtils.convertStringToDate("yyyy-MM-dd HH:mm", DateUtils.formatDate("yyyy-MM-dd HH:mm", new Date()));
        Date tradingdate = DateUtils.convertStringToDate("yyyy-MM-dd HH:mm", DateUtils.formatDate(date)+" "+time[0]);
        if (tradingdate.getTime() > date.getTime()){
            optionSymbolKey = checkRedisKey(Constant.OPTION_SYMBOL_INFO);
        }else {
            String today = getWorkDate(DateUtils.formatDate("yyyy-MM-dd", new Date()));
            optionSymbolKey = Constant.OPTION_SYMBOL_INFO + today;
        }
        Object optionSymbolObj=redisTemplate.opsForHash().get(optionSymbolKey, optionMarketDataField.getInstrumentCode());
        if(optionSymbolObj==null){
            return null;
        }
        OptionSymbol optionSymbol=JSONObject.parseObject(optionSymbolObj.toString(),OptionSymbol.class);
        optionMarketDataField.setDeliveryYear(optionSymbol.getDeliveryYear());
        optionMarketDataField.setDeliveryMonth(optionSymbol.getDeliveryMonth());
        optionMarketDataField.setInstrumentMonth(optionSymbol.getInstrumentMonth());
        optionMarketDataField.setInstrumentType(optionSymbol.getInstrumentType());
        optionMarketDataField.setTargetCode(optionSymbol.getTargetCode());
        optionMarketDataField.setRemainderDays(optionSymbol.getRemainderDays());
        optionMarketDataField.setExpireDay(optionSymbol.getExpireDay());
        optionMarketDataField.setInstrumentName(optionSymbol.getInstrumentName());
        if(StringUtils.isNotBlank(optionSymbol.getPreClosePrice())){
            optionMarketDataField.setPreClosePrice(optionSymbol.getPreClosePrice());
        }
        return optionMarketDataField;
    }

    /**
     * 获取新浪分时线数据（初）
     * @param record
     * @return
     */
    @Override
    public Object getSinaMinLine(TradingVo record){
        switch (record.getType()) {
            case "0":
                String sinaMinLine = mdRemoteCall.getSinaOptionMinLine(record.getInstrumentCode());
                JSONObject jsonObject = JSON.parseObject(JSON.parseObject(sinaMinLine).get("result").toString());
                JSONArray jsonArray = JSON.parseArray(jsonObject.get("data").toString());
                if (jsonArray.size() == 0){
                    String sinaFiveDayLine = mdRemoteCall.getSinaOptionFiveDayLine(record.getInstrumentCode());
                    jsonObject = JSON.parseObject(JSON.parseObject(sinaFiveDayLine).get("result").toString());
                    jsonArray = JSON.parseArray(jsonObject.get("data").toString());
                    jsonArray = jsonArray.getJSONArray(jsonArray.size()-1);
                }
                JSONArray jsonArrayS = new JSONArray();
                try {
                    String nowDateStr=DateUtils.convertDateToString(new Date());
                    Date beginTime= DateUtils.convertStringToDate("yyyy-MM-dd HH:mm", nowDateStr + " 11:30");
                    Date endTime=DateUtils.convertStringToDate("yyyy-MM-dd HH:mm", nowDateStr +" 13:00");
                    int a = 0;
                    for (int i = 0; i < jsonArray.size(); i++){//去除新浪中无效数据
                        JSONObject jsonObjets = JSON.parseObject(jsonArray.get(i).toString());
                        Date nowDate= DateUtils.convertStringToDate("yyyy-MM-dd HH:mm", nowDateStr + " " + jsonObjets.get("i"));
                        if(!DateUtils.belongCalendar(nowDate, beginTime, endTime)) {
                            jsonArrayS.add(a, jsonArray.get(i));
                            a++;
                        }
                    }
                }catch (Exception ex){
                    ex.getMessage();
                }
                return jsonArrayS;
            case "1":
                String sinaDayLine = mdRemoteCall.getSinaOptionDayLine(record.getInstrumentCode());
                JSONObject json = JSON.parseObject(JSON.parseObject(sinaDayLine).get("result").toString());
                return json.get("data");
            case "2":
                return mdRemoteCall.getEastmoneyMonthLine(record.getInstrumentCode());
        }
        return null;
    }

    /**
     * 获取所有合约信息
     * @return
     */
    @Override
    public List<OptionSymbol> getContractList(){
        List<OptionSymbol> optionSymbolList = new LinkedList<OptionSymbol>();
        String key = checkRedisKey(Constant.OPTION_SYMBOL_INFO.substring(0, Constant.OPTION_SYMBOL_INFO.length()-1));
        Map<Object, Object> target = redisTemplate.opsForHash().entries(key);
        if (target.size() > 0) {
            for (Object mapKey : target.keySet()) {
                optionSymbolList.add(JSONObject.parseObject(target.get(mapKey).toString(), OptionSymbol.class));
            }
        }
        return optionSymbolList;
    }

    /**
     * 判断key是否存在，获取最新key
     * @param key
     * @return
     */
    @Override
    public String checkRedisKey(String key){
        try {
            Date date = new Date();
            for (int i = 0; i <= 20; i++) {
                String keyDate = DateUtils.convertDateToString(DateUtils.addDay(date, -i));
                if (":".equals(key.substring(key.length() - 1, key.length()))){
                    keyDate = key + keyDate;
                }else {
                    keyDate = key + ":" + keyDate;
                }
                if (redisTemplate.hasKey(keyDate)) {
                    return keyDate;
                }
            }
            return null;
        }catch (Exception ex){
            LOGGER.error(ex.getMessage());
            return null;
        }
    }

    /**
     * 校验当前时间是否在交易时间段内
     * @param tradingTime
     * @return
     */
    @Override
    public boolean checkTradingTime(String tradingTime, Response response){
        boolean flag=false;
        try {
            /**dayType 工作日对应结果为 0, 休息日对应结果为 1, 节假日对应的结果为 2**/
            if (response.isSuccess() && response.getDayType()!=0){
                return flag;
            }
            //如果是工作日 则直接校验时间段
            if(response.isSuccess() && response.getDayType()==0){
                String [] tradingTimes=tradingTime.split("\\|");
                for(String time:tradingTimes){
                    String [] timeSlot = time.split("-");
                    String nowDateStr=DateUtils.convertDateToString(new Date());
                    Date beginTime= DateUtils.convertStringToDate("yyyy-MM-dd HH:mm", nowDateStr + " " + timeSlot[0]);
                    Date endTime=DateUtils.convertStringToDate("yyyy-MM-dd HH:mm",nowDateStr+" "+timeSlot[1]);
                    if(DateUtils.belongCalendar(new Date(), beginTime, endTime)){
                        flag = true;
                    }
                }
            }
            return flag;
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Map<String,Object> getKLineList(KLineDto kLineDto) throws Exception{
        Map<String,Object> map=null;
        OptionTradingGoods optionTradingGoods=null;
        Date nowDate=new Date();
        String todayStr=DateUtils.convertDateToString(nowDate);
        String optionSymbolKey=checkRedisKey(Constant.OPTION_SYMBOL_INFO);
        Object optionSymbol=redisTemplate.opsForHash().get(optionSymbolKey, kLineDto.getCode());
        if(optionSymbol!=null){
            JSONObject optionSybol2Json=JSONObject.parseObject(optionSymbol.toString());
            String targetCode=optionSybol2Json.getString("targetCode");
            Object optionTradingGoodsObj=redisTemplate.opsForValue().get(Constant.TRADE_DATE_INFO + targetCode);
            optionTradingGoods=JSONObject.parseObject(optionTradingGoodsObj.toString(), OptionTradingGoods.class);
        }else{
            return null;
        }
        Response response=mdRemoteCall.checkHoliday(todayStr);
        if(kLineDto.getKlineType()==0 || kLineDto.getKlineType()==1){
            map=this.getQuotationsKlineOneMin(kLineDto,optionTradingGoods,response);
        }else{
            map=this.getQuotationsKlineByType(kLineDto,optionTradingGoods,response);
        }
        return map;
    }

    @Override
    public List<MarketTradeDetail> getMarketTradeDetail(TradingVo tradingVo) {
        List<MarketTradeDetail> marketTradeDetails=null;
        String today=DateUtils.convertDateToString(new Date());
        String collectionName=this.getMongoCollectionName(tradingVo.getInstrumentMonth(),today,15);
        if(StringUtils.isBlank(collectionName)){
            return marketTradeDetails;
        }
        Query query = new Query();
        final Pageable pageableRequest = new PageRequest(tradingVo.getPageNum(), tradingVo.getPageSize());
        Criteria criteria = Criteria.where("code").is(tradingVo.getInstrumentCode());
        query.addCriteria(criteria);
        query.with(new Sort(Sort.Direction.DESC, "marketTime"));
        //分页查询
        query.with(pageableRequest);
        long l1=System.currentTimeMillis();
        marketTradeDetails=mongoTemplate.find(query,MarketTradeDetail.class, collectionName);
        long l2=System.currentTimeMillis();
        LOGGER.info("执行时间--->" + (l2 - l1));
        /**计算现手**/
        int num=0;
        for(MarketTradeDetail marketTradeDetail:marketTradeDetails){
            num++;
            if(num<marketTradeDetails.size()){
                Double nextVolume=Double.valueOf(marketTradeDetails.get(num).getVolume());
                Double curTradeVolume=Double.valueOf(marketTradeDetail.getVolume())-nextVolume;
                marketTradeDetail.setCurTradeVolume(String.valueOf(curTradeVolume));
            }else{
                marketTradeDetail.setCurTradeVolume(String.valueOf(0));
            }
        }
        return marketTradeDetails;
    }

    private String getMongoCollectionName(String instrumentMonth,String today,int version){
        try {
            String collectionName=Constant.MARKET_TRADE_DETAIL+instrumentMonth+"_"+today;
            boolean exists=mongoTemplate.collectionExists(collectionName);
            /**不存在 则递归去查**/
            if(!exists && version>0){
                String yesterday=DateUtils.convertDateToString(DateUtils.minusDay(DateUtils.convertStringToDate(today), 1));
                version--;
                collectionName=this.getMongoCollectionName(instrumentMonth,yesterday,version);
            }
            return collectionName;
        }catch (Exception e){
            return null;
        }
    }

    /**
     * K线类型 0-当日分时线；1-1分钟K线；2-5分钟K线；3-15分钟K线；4-30分钟K线；5-1小时K线；6-4小时；7-日线
     * 获取一分钟K线
     * @param kLineDto
     * @return
     */
    private Map<String,Object> getQuotationsKlineOneMin(KLineDto kLineDto,OptionTradingGoods optionTradingGoods,Response response) throws Exception{
        final Pageable pageableRequest = new PageRequest(kLineDto.getPageNum(), kLineDto.getPageSize());
        Map<String,Object> map=new HashMap<>();
        List<KLineEntity> kLineEntities=null;
        Date nowDate=new Date();
        Query query = new Query();
        /**根据合约月份找历史合约**/
        Criteria criteria=new Criteria();
        String beginDate="";
        /**查询当日分时线**/
        if(kLineDto.getKlineType()==0){
            //获取当前星期几
            Calendar calendar=Calendar.getInstance();
            /**6-星期六 0-星期日 1-星期一 ...**/
            int week=calendar.get(Calendar.DAY_OF_WEEK)-1;
            Integer currentHour=Integer.valueOf(DateUtils.getDateTime("HH",nowDate));
            switch (week){
                case 0:
                    beginDate=DateUtils.getDateTime("yyyy-MM-dd",DateUtils.addDay(nowDate, -2))+" 20:55:00";
                    break;
                case 1:
                    /**当前时间大于21点获取新的一个交易日的k线**/
                    if(currentHour>=21){
                        beginDate=DateUtils.getDateTime("yyyy-MM-dd",DateUtils.addDay(nowDate, 0))+" 20:55:00";
                    }else{
                        beginDate=DateUtils.getDateTime("yyyy-MM-dd",DateUtils.addDay(nowDate, -3))+" 20:55:00";
                    }
                    break;
                case 6:
                    beginDate=DateUtils.getDateTime("yyyy-MM-dd",DateUtils.addDay(nowDate, -1))+" 20:55:00";
                    break;
                default:
                    /**获取新的一个交易日的k线**/
                    if(currentHour>=21){
                        beginDate=DateUtils.getDateTime("yyyy-MM-dd",DateUtils.addDay(nowDate, 0))+" 20:55:00";
                    }else{
                        beginDate=DateUtils.getDateTime("yyyy-MM-dd",DateUtils.addDay(nowDate, -1))+" 20:55:00";
                    }
                    break;
            }
            /**递归获取交易日的一分钟k线分时图**/
            kLineEntities=this.supplementKLineEntity(getTodayOneMinKLine(beginDate, kLineDto.getCode(), kLineDto.getInstrumentMonth(), 20),optionTradingGoods.getTradingTime());
            Long minNum=this.getMinNum(optionTradingGoods.getTradingTime());
            /**获取分钟数**/
            map.put("minNum",minNum);
            LOGGER.warn("minNum...........:"+minNum);
        }
        /**查询1分钟K线条件**/
        if(kLineDto.getKlineType()==1){
            criteria = Criteria.where("code").is(kLineDto.getCode());
            query.addCriteria(criteria);
            query.with(new Sort(Sort.Direction.DESC, "curTime"));
            //分页查询
            query.with(pageableRequest);
            kLineEntities=mongoTemplate.find(query,KLineEntity.class, Constant.QUOTATIONS_KLINE_ONE_MIN+kLineDto.getInstrumentMonth());
        }

        /**如果是第一页的话且为开市时 查询正在进行的一分钟内的最高和最低价**/
        if(kLineDto.getPageNum()==0 && this.checkTradingTime(optionTradingGoods.getTradingTime(),response)){
            KLineEntity kLineEntity=this.getUnderwayKline(Constant.UNDERWAY_KLINE_ONE_MIN,kLineDto.getCode());
            if(kLineEntity!=null){
                LOGGER.warn("从内存当中获取到的高开低收：" + kLineEntity.toString());
                kLineEntities.add(0, kLineEntity);
            }

        }
        Integer kLineEntitiesSize=kLineEntities.isEmpty()==true?0:kLineEntities.size();
        LOGGER.warn("kLineEntities.size.........:" + kLineEntitiesSize);
        map.put("list",kLineEntities);
        return map;
    }

    /**
     * K线类型 0-当日分时线；1-1分钟K线；2-5分钟K线；3-15分钟K线；4-30分钟K线；5-1小时K线；6-4小时；7-日线
     * @param kLineDto
     * @return
     */
    private Map<String,Object> getQuotationsKlineByType(KLineDto kLineDto,OptionTradingGoods optionTradingGoods,Response response) throws Exception{
        final Pageable pageableRequest = new PageRequest(kLineDto.getPageNum(), kLineDto.getPageSize());
        Map<String,Object> map=new HashMap<>();
        Query query = new Query();
        /**根据合约月份找历史合约**/
        Criteria criteria=Criteria.where("code").is(kLineDto.getCode());
        query.addCriteria(criteria);
        query.with(new Sort(Sort.Direction.DESC, "curTime"));
        query.with(pageableRequest);
        List<KLineEntity> kLineEntities=null;
        String kLineConllection="";
        Integer redisKlineKey=null;
        switch (kLineDto.getKlineType()){
            case 2:
                kLineConllection=Constant.QUOTATIONS_KLINE_FIVE_MIN;
                break;
            case 3:
                kLineConllection=Constant.QUOTATIONS_KLINE_FIFTEEN_MIN;
                break;
            case 4:
                kLineConllection=Constant.QUOTATIONS_KLINE_THIRTY_MIN;
                break;
            case 5:
                kLineConllection=Constant.QUOTATIONS_KLINE_ONE_HR;
                break;
            case 6:
                kLineConllection=Constant.QUOTATIONS_KLINE_FOUR_HR;
                break;
            case 7:
                kLineConllection=Constant.QUOTATIONS_KLINE_DAY;
                break;
            default:
                break;
        }
        kLineEntities=mongoTemplate.find(query,KLineEntity.class, kLineConllection+kLineDto.getInstrumentMonth());
        /**如果是第一页的话并且当前是交易时间的话则到redis查询正在进行的一分钟内的最高和最低价**/
        if(kLineDto.getPageNum()==0 && this.checkTradingTime(optionTradingGoods.getTradingTime(),response)){
            KLineEntity kLineEntity=this.getUnderwayKline(kLineDto.getKlineType(), kLineDto.getCode());
            if(kLineEntity!=null){
                LOGGER.warn("从内存当中获取到的高开低收：" + kLineEntity.toString());
                kLineEntities.add(0, kLineEntity);
            }
        }
        map.put("list", kLineEntities);
        return map;
    }

    /**
     * 递归获取交易日的一分钟k线分时图
     * @param beginDate
     * @param instrumentCode 合约code
     * @param instrumentMonth 合约月份
     * @param version 递归次数
     * @return
     * @throws Exception
     */
    private List<KLineEntity> getTodayOneMinKLine(String beginDate,String instrumentCode,String instrumentMonth,int version)throws Exception{
        version--;
        LOGGER.warn("version value..............." + version);
        Query query = new Query();
        /**根据合约月份找历史合约**/
        Criteria criteria=new Criteria();
        /**mongodb+8小时 时区问题**/
        Date beginDates=DateUtils.addHour(DateUtils.convertStringToDate("yyyy-MM-dd HH:mm:ss", beginDate), 8);
        //大于等于开始时间
        criteria = Criteria.where("code").is(instrumentCode).and("curTime").gte(beginDates);
        query.addCriteria(criteria);
        query.with(new Sort(Sort.Direction.DESC, "curTime"));
        LOGGER.warn("collectionName--->:" + Constant.QUOTATIONS_KLINE_ONE_MIN + instrumentMonth + "\r\nquery--->:" + query.toString());
        List<KLineEntity> kLineEntities=mongoTemplate.find(query,KLineEntity.class, Constant.QUOTATIONS_KLINE_ONE_MIN+instrumentMonth);
        if((kLineEntities==null || kLineEntities.size()==0) && version>0){
            Date nowDate=DateUtils.convertStringToDate("yyyy-MM-dd HH:mm:ss", beginDate);
            beginDate=DateUtils.getDateTime("yyyy-MM-dd",DateUtils.addDay(nowDate, -1))+" 20:55:00";
            kLineEntities=getTodayOneMinKLine(beginDate,instrumentCode,instrumentMonth,version);
        }
        return kLineEntities;
    }
    /**
     * 获取该合约开市的分钟数
     * @param tradingTime
     * @return
     */
    private Long getMinNum(String tradingTime){
        Long minNum=0L;
        String [] tradingTimes=tradingTime.split("\\|");
        for(String time:tradingTimes){
            String [] timeSlot = time.split("-");
            try {
                Date beginTime=null,endTime=null;
                String nowDateStr=DateUtils.convertDateToString(new Date());
                beginTime= DateUtils.convertStringToDate("yyyy-MM-dd HH:mm", nowDateStr + " " + timeSlot[0]);
                Integer currentHour=Integer.valueOf(DateUtils.getDateTime("HH", beginTime));
                endTime=DateUtils.convertStringToDate("yyyy-MM-dd HH:mm",nowDateStr+" "+timeSlot[1]);
                if(currentHour==21 && beginTime.after(endTime)){
                    endTime=DateUtils.addDay(endTime,1);
                }
                long between=(endTime.getTime()-beginTime.getTime())/1000;//除以1000是为了转换成秒
                long min=between/60;
                LOGGER.warn(time + "min:" + min);
                minNum+=min;
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return minNum;
    }

    @Async("executorPool")
    @Override
    public void sendMongodbTickDetail(String instrumentMonth, String nowDate, OptionMarketTickDataField optionMarketTickDataField) {
        try {
            /**先查下是否存在**/
            String nowTickTime=nowDate+" "+optionMarketTickDataField.getUpdateTime();
            Date marketTime = DateUtils.addHour(DateUtils.convertStringToDate("yyyy-MM-dd HH:mm:ss", nowTickTime), 8);
            String collectionName=Constant.MARKET_TRADE_DETAIL + instrumentMonth+"_"+nowDate;
            Query query = new Query();
            Criteria criteria = Criteria.where("code").is(optionMarketTickDataField.getInstrumentCode())
                    .and("volume").is(optionMarketTickDataField.getVolume())
                    .and("marketTime").is(marketTime);
            query.addCriteria(criteria);
            MarketTradeDetail marketTradeDetail=mongoTemplate.findOne(query, MarketTradeDetail.class, collectionName);
            if(marketTradeDetail==null){
                /**存mongo数据**/
                marketTradeDetail=new MarketTradeDetail();
                marketTradeDetail.setCode(optionMarketTickDataField.getInstrumentCode());
                marketTradeDetail.setLastPrice(optionMarketTickDataField.getLastPrice());
                marketTradeDetail.setVolume(optionMarketTickDataField.getVolume());
                marketTradeDetail.setMarketTime(marketTime);
                marketTradeDetail.setCreateTime(DateUtils.parseToDateTimeStr(new Date()));
                String locIp= LocalInetAddress.getLocalAddress();
                /**指定服务器进行存储**/
                if(Constant.MONGODB_INSERT_IP.contains(locIp)){
                    mongoTemplate.insert(marketTradeDetail, collectionName);
                }
                /**推送之前将增加的8小时减去 再推送**/
                marketTradeDetail.setMarketTime(DateUtils.convertStringToDate("yyyy-MM-dd HH:mm:ss", nowTickTime));
                SocketJsonData<MarketTradeDetail> socketJsonData=new SocketJsonData<MarketTradeDetail>(Constant.NOW_VOLUME,marketTradeDetail);
                //深度行情json
                Object marketDataFieldToJson= JSONObject.toJSON(socketJsonData);
                //二进制推送 推送压缩后的包
                byte [] data= GZIPUtils.compress(marketDataFieldToJson.toString());
                ByteBuf byteBuf = Unpooled.buffer(data.length * 3);
                byteBuf.writeBytes(data);
                ChannelGroups.writeByChannelName(Constant.CHANNEL_MAP_NOW_VOLUME, new BinaryWebSocketFrame(byteBuf));
                LOGGER.info(socketJsonData.getData().getCode() + ":sendMongodbTickDetail推送的格式：" + marketDataFieldToJson);
            }
        }catch (Exception e){
            LOGGER.warn("sendMongodbTickDetail error ..........." + e);
        }
    }

    /**
     * 每天创建索引清除昨天的数据
     */
    @Override
    public void createIndexAndRemoveYesterdayColl(){
        try {
            String nowDate=DateUtils.convertDateToString(new Date());
            /**先获取标的**/
            Set<Object> targetCodes=redisTemplate.opsForHash().keys(Constant.TARGET_CODE_LIST);
            for(Object targetCode:targetCodes){
                String monthSetKey=Constant.INSTRUMENT_MONTH_SET+targetCode.toString()+":"+nowDate;
                Set<String> instrumentMonths=redisTemplate.opsForSet().members(monthSetKey);
                for(String instrumentMonth:instrumentMonths){
                    String collectionName=Constant.MARKET_TRADE_DETAIL + instrumentMonth+"_"+nowDate;
                    mongoTemplate.getCollection(collectionName).createIndex("code");
                    mongoTemplate.getCollection(collectionName).createIndex("volume");
                    mongoTemplate.getCollection(collectionName).createIndex("marketTime");
                    LOGGER.info("createIndexColl---->" + collectionName + " is success");
                    /**删除上一个交易日的数据**/
                    this.removeYesterdayColl(nowDate,instrumentMonth,15);
                }
            }
        }catch (Exception e){
           LOGGER.error("createIndexAndRemoveYesterdayColl is error", e);
        }
    }

    /**
     * 删除前一个交易日的数据
     * @param nowDate
     * @param instrumentMonth
     */
    private void removeYesterdayColl(String nowDate,String instrumentMonth,int version) throws Exception{
        String yesterday=DateUtils.convertDateToString(DateUtils.minusDay(DateUtils.convertStringToDate(nowDate), 1));
        String collectionName=Constant.MARKET_TRADE_DETAIL + instrumentMonth+"_"+yesterday;
        boolean exists=mongoTemplate.collectionExists(collectionName);
        if(exists){
            mongoTemplate.dropCollection(collectionName);
            LOGGER.info("removeYesterdayColl---->"+collectionName+" is success");
        }else if(!exists && version>=0){
            version--;
            this.removeYesterdayColl(yesterday,instrumentMonth,version);
        }
    }

    /**
     * 查询正在进行的最高最低
     * @param kLineType
     * @param fidle
     * @return
     * @throws Exception
     */
    private KLineEntity getUnderwayKline(Integer kLineType,String fidle)throws Exception{
        String kLineStr="";
        switch (kLineType){
            case 1:kLineStr=NativeMemoryConfig.UNDERWAY_KLINE_ONE_MIN.get(fidle);break;
            case 2:kLineStr=NativeMemoryConfig.UNDERWAY_KLINE_FIVE_MIN.get(fidle);break;
            case 3:kLineStr=NativeMemoryConfig.UNDERWAY_KLINE_FIFTEEN_MIN.get(fidle);break;
            case 4:kLineStr=NativeMemoryConfig.UNDERWAY_KLINE_THIRTY_MIN.get(fidle);break;
            case 5:kLineStr=NativeMemoryConfig.UNDERWAY_KLINE_ONE_HR.get(fidle);break;
            case 6:kLineStr=NativeMemoryConfig.UNDERWAY_KLINE_FOUR_HR.get(fidle);break;
            case 7:kLineStr=NativeMemoryConfig.UNDERWAY_KLINE_DAY.get(fidle);break;
            default:LOGGER.warn("传入的类型有误");break;
        }
        KLineEntity kLineEntity=null;
        if(StringUtils.isNotBlank(kLineStr)){
            String [] kLineArray=kLineStr.split("\\|");
            //underwayKline|k线类型|FG809|2018-08-13 11:04:13|1466.000|1466.000|1467.000|1466.000|12724|0.00|53282.000|FG|09|
            String code=kLineArray[2],curTime=kLineArray[3],open=kLineArray[4],close=kLineArray[5],high=kLineArray[6],low=kLineArray[7], volume = kLineArray[8],
                    tradeAmt=kLineArray[9], positionNum=kLineArray[10], instrumentMonth=kLineArray[12];
            kLineEntity=new KLineEntity();
            kLineEntity.setCode(code);
            kLineEntity.setOpen(open);
            kLineEntity.setClose(close);
            kLineEntity.setHigh(high);
            kLineEntity.setLow(low);
            kLineEntity.setVolume(volume);
            kLineEntity.setTradeAmt(tradeAmt);
            kLineEntity.setPositionNum(positionNum);
            LOGGER.warn("curTimeStr:" + curTime);
            Date curDateTime=DateUtils.addHour(DateUtils.convertStringToDate("yyyy-MM-dd HH:mm:ss", curTime), 8);
            kLineEntity.setCurTime(curDateTime);
            kLineEntity.setInstrumentMonth(instrumentMonth);
//            kLineEntity.setAvgPrc(avgPrc);
        }
        return kLineEntity;
    }

    /**
     * 补充K线数据
     * @param kLineEntityList
     * @return
     */
    public List<KLineEntity> supplementKLineEntity(List<KLineEntity> kLineEntityList,String tradeTime){
        try {
            LinkedList<KLineEntity> linkedKLineEntityList=new LinkedList();
            for (int i = 0; i < kLineEntityList.size(); i++) {
                int nextI=i+1;
                if(nextI==kLineEntityList.size()){
                    break;
                }
                /**当前这一个K线对象**/
                KLineEntity kLineEntity=kLineEntityList.get(i);
                linkedKLineEntityList.add(kLineEntity);
                /**获取下一个K线对象**/
                KLineEntity nextKLineEntity=kLineEntityList.get(nextI);
                /**格式化K线时间**/
                /**当前时间加一分钟的时间**/
                String curTimeStr=DateUtils.getDateTime("HH:mm",DateUtils.addMinute(kLineEntity.getCurTime(), -1));
                String nextCurTimeStr=DateUtils.getDateTime("HH:mm",nextKLineEntity.getCurTime());
                /**如果两个不相等 则说明中间有断的**/
                if(!curTimeStr.equals(nextCurTimeStr)){
                    /**计算中间差几个**/
                    Date curTime=DateUtils.convertStringToDate("HH:mm",curTimeStr);
                    Date nextCurTime=DateUtils.convertStringToDate("HH:mm",nextCurTimeStr);
                    /**相差多少分钟**/
                    LOGGER.warn("startM:"+nextCurTime+",endM:"+curTime);
                    Integer spaceMin=0;
                    if(nextCurTime.getTime()<=curTime.getTime()){
                        spaceMin=Integer.parseInt(DurationFormatUtils.formatPeriod(nextCurTime.getTime(),curTime.getTime() , "m"));
                    }
                    /**开始补充**/
                    for(int j=0;j<spaceMin;j++){
                        KLineEntity nextKLineEntityBak=new KLineEntity(nextKLineEntity);
                        nextKLineEntityBak.setCurTime(DateUtils.addMinute(nextKLineEntityBak.getCurTime(), spaceMin - j));
                        nextKLineEntityBak.setVolume("0");
                        if(checkMdTradingTime(nextKLineEntityBak.getCurTime(), tradeTime)){
                            linkedKLineEntityList.add(linkedKLineEntityList.size(), nextKLineEntityBak);
                        }
                    }
                }
            }
            LOGGER.warn("linkedKLineEntityList.size-------------->"+linkedKLineEntityList.size());
            return linkedKLineEntityList;
        }catch (Exception e){
            LOGGER.error("supplementKLineEntity error",e);
            return kLineEntityList;
        }
    }

    /**
     * 校验行情是否再交易时间
     * @param nowDate
     * @param tradingTime
     * @return
     */
    private boolean checkMdTradingTime(Date nowDate,String tradingTime){
        boolean flag=false;
        try {
            nowDate=DateUtils.addHour(nowDate,-8);
            Integer currentTimeHour=Integer.valueOf(DateUtils.getDateTime("HH", nowDate));
            String [] tradingTimes=tradingTime.split("\\|");
            for(String time:tradingTimes){
                String [] timeSlot = time.split("-");
                Date beginTime=null,endTime=null;
                String nowDateStr=DateUtils.convertDateToString(nowDate);
                beginTime= DateUtils.convertStringToDate("yyyy-MM-dd HH:mm", nowDateStr + " " + timeSlot[0]);
                Integer beginHour=Integer.valueOf(DateUtils.getDateTime("HH", beginTime));
                endTime=DateUtils.convertStringToDate("yyyy-MM-dd HH:mm",nowDateStr+" "+timeSlot[1]);
                Integer endTimeHour=Integer.valueOf(DateUtils.getDateTime("HH", endTime));
                if(beginHour==21 && endTimeHour<23){
                    if(currentTimeHour>3){
                        endTime=DateUtils.addDay(endTime,1);
                    }else{
                        beginTime=DateUtils.addDay(beginTime,-1);
                    }
                }
                flag=DateUtils.belongCalendar(nowDate,beginTime,endTime);
                if(flag){
                    break;
                }
            }
            return flag;
        } catch (ParseException e) {
            LOGGER.error("checkMdTradingTime......."+e);
        }finally {
            return flag;
        }
    }
}
